<template>
	<view class="page">
		<view class="nav-style" :style="{'height':navHeight+'px'}">
			<image v-if="this.step!=1" class="back-img" src="/static/img/back.png" mode="aspectFit" :style="{'top':statusBarHeight+'px'}"
				@click="back"></image>
			<image class="small-logo" src="/static/img/logo-white.png" mode="aspectFit"
				:style="{'padding-top':statusBarHeight+'px'}"></image>
		</view>
		<view v-if="[4, 5].includes(info.step)" class="process-wrap" :style="{'padding-top': (navHeight + 20) +'px'}">
			<process :active="info.step" :steps="collectionStepsData" />
		</view>
		<!--    <image class="header" src="/static/image/header.png" mode="aspectHeightFit" />-->
		<view class="wrap" :style="{'margin-top': [1, 2, 3, 6, 7].includes(info.step) ? navHeight + 'px' : '' }">
			<test-check ref="testCheck" :info="info" :time="times" :device-number="deviceNumber" @back="back"
				@next="onConfirm" @Close='Shutdown' />
		</view>

		<uni-popup ref="popup" :mask-click="false" :is-mask-click="false" type="center">
			<view class="popup-wrap">
				<image class="popup-bg" src="/static/img/tips-bg.png" mode="aspectFit" />
				<view class="popup-container">
					<view class="popup-title">
						<image class="popup-img" src="/static/img/tips-icon.png" mode="aspectFit" />
						<view class="popup-text">温馨提示</view>
					</view>
					<view class="popup-content">疾控中心将在保障您隐私的前提下，提供进一步检测、知识咨询、预防措施等服务，请问您是否需要？</view>
					<view class="popup-btn-wrap">
						<view class="popup-btn cancel" @click="onCancel">不需要</view>
						<view class="popup-btn need" @click="onNeed">需要（推荐）</view>
						<view class="popup-btn-close  cancel" @click="Shutdown">关机</view>
					</view>
				</view>
			</view>
		</uni-popup>



	</view>
</template>

<script>
	import store from '@/store'
	import TestCheck from '@/pages/home/components/test-check/index.vue'
	import Process from '../../components/process/index.vue'
	import {
		decodeBase64MAC
	} from "@/utils/base64.js";
	import {
		ab2hex,
		sleep,
		stringToHex,
		debounce
	} from '@/utils/util.js'
	import {
		Getresult,
		UpReagentResult,
		ConvertCoordinate,
		aesDecryptjieguozhi,
		aesDecrypt2,
		GetReleted,
		CreateReleted,
		AESEncrypt,
		AESDecrypt,
		CreateReagentResult,
		UpdateReagentResult,
		ReportedData,
		aesDecryptGetAPiyuzhi,
		Base64
	} from '@/utils/api.js'
	const baseSecret = '4B65487561BFC6'
	// const HANDLE_0x1800 = '00001800-0000-1000-8000-00805F9B34FB'
	// const HANDLE_0x2A00 = '00002A00-0000-1000-8000-00805F9B34FB'
	const HANDLE_0x9000 = '00009000-0000-1000-8000-00805F9B34FB'
	const HANDLE_0x9001 = '00009001-0000-1000-8000-00805F9B34FB'
	const HANDLE_0x9002 = '00009002-0000-1000-8000-00805F9B34FB'
	const HANDLE_0x9003 = '00009003-0000-1000-8000-00805F9B34FB'
	const HANDLE_0x9004 = '00009004-0000-1000-8000-00805F9B34FB'
	const HANDLE_0x9005 = '00009005-0000-1000-8000-00805F9B34FB'
	const HANDLE_0x9006 = '00009006-0000-1000-8000-00805F9B34FB'
	const HANDLE_0x9007 = '00009007-0000-1000-8000-00805F9B34FB'
	let that = null
	export default {
		name: 'Home',
		components: {
			TestCheck,
			Process
		},
		data() {
			return {
				HFX:"",
				JG:false,
				JG_2:0,
				weiwancheng:false,
				managePhone: '',
				gps: false,
				// processTimer: null,
				processIndex: 1,
				isStartDiscovery: false,
				timer: null,
				checkTimer: null,
				resultTimer: null,
				navHeight: '',
				statusBarHeight: '',
				DetectionType: '',
				showNav: true,
				times: 0,
				step: 1,
				info: {},
				devicesList: [],
				blueDeviceList: [],
				blueDeviceList_1: [],
				process: [],
				searching: false,
				deviceNumber: '',
				scanDeviceName: '',
				scanMac: '',
				// deviceName: '',
				deviceId: '',
				serviceId: '',
				characteristicId: '',
				key: '',
				iv: '',
				// readStepsData: [
				//   {
				//     step: 1,
				//     name: '材料检查'
				//   },
				//   {
				//     step: 2,
				//     name: '操作准备'
				//   },
				//   {
				//     step: 3,
				//     name: '开启设备'
				//   },
				//   {
				//     step: 4,
				//     name: '扫码连接'
				//   }
				// ],
				collectionStepsData: [{
						step: 2,
						name: '采血'
					},
					{
						step: 3,
						name: '检测'
					}
				],
				stepData: [{
						step: 1,
						steps: [{
								step: 1,
								imageNum: 1,
								name: '材料检查',
								image: 'step-check.png',
								content: ['请检查电子检测盒、采血针、滴管、酒精棉片、缓冲液等内容物是否齐全。'],
							},
							{
								step: 2,
								imageNum: 2,
								name: '操作准备',
								image: 'step-operate.png',
								content: ['1、洗手并消毒，在做测试前，手需要完全擦干；', '2、将电子检测盒取出，放在室温中；', '3、确认电子检测盒的效期在可使用范围内；',
									'4、在撕口处打开铝箔袋，取出电子检测盒，滴液口向上，平放于桌面。'
								],
							},
							{
								step: 3,
								imageNum: 3,
								name: '开启设备',
								image: 'step-turn-on.png',
								content: ['1、请拔出电池阻断塑料片；', '2、将电子检测盒放在距离手机50cm以内；', '3、观看电子检测盒指示灯是否闪烁。'],
							},
							{
								step: 4,
								imageNum: 4,
								name: '扫码连接',
								image: 'step-connect.png',
								content: ['1、寻找到电子检测盒上二维码；', '2、请点击下方扫一扫；', '3、扫描二维码进行蓝牙连接。'],
							}
						],
						operateName: '扫一扫',
					},
					// 连接失败
					{
						step: 2, // 5
						imageNum: 5,
						name: '连接电子检测盒',
						contentTitle: '请按以下说明进行检查',
						image: 'step-fail.png',
						imageDesc: '连接失败！',
						content: ['1、保持电子检测盒在开机状态；', '2、检查手机蓝牙，保持开启状态；', '3、将手机与电子检测盒尽量靠近，完成蓝牙配对；',
							'4、电子检测盒未连接到其他的手机'],
						operateName: '重新扫描',
					},
					// 连接成功
					{
						step: 3, // 6
						imageNum: 6,
						name: '连接电子检测盒',
						image: 'step-success.png',
						custom: true,
						imageDesc: '连接成功！',
						operateName: '开始检测',
					},
					{
						step: 4, // 7
						imageNum: 7,
						name: '指尖血采集',
						image: 'step-collection.png',
						content: ['先用酒精棉片擦拭取血部位，待酒精挥发后采用一次性采血针刺破皮肤采血，用滴管吸取血液。'],
						operateName: '下一步',
					},
					{
						step: 5, // 8
						imageNum: 8,
						name: '加样检测',
						image: 'step-add.png',
						content: ['用滴管吸取一定量的血液样本，然后垂直滴入2滴样本（约 50μl）到加样孔中，并滴加两滴（约 80μl）缓冲液。'],
						operateName: '开始检测',
					},
					{
						step: 6, // 9
						imageNum: 9,
						name: '倒计时',
						contentTitle: '请按以下说明进行',
						content: ['1、请保持电子检测盒平放，耐心等待；', '2、请勿退出应用程序；', '3、请勿将手机拿开检测仪超过50cm的距离。'],
						operateName: '',
						timer: 0
					},
					{
						step: 7, // 10
						imageNum: 10,
						name: '检测结果',
						contentTitle: '检测结果说明',
						content: ['检测完成后，请将电子检测盒、滴管以及其他组件放置于废弃物袋中，并密封。'],
						operateName: '',
						result: 0,
					}
				]
			}
		},
		beforeDestroy() {
			that = null
			this.resultTimer = null
			this.timer = null
		},
		onHide(){
			console.log('用户隐藏了小程序')
			this.close()
			this.step = 1
			this.info = this.stepData[this.step - 1]
		},
		onLoad(op) {
			console.log(op);
			this.weiwancheng=false
			this.JG=false
			this.JG_2=0
			this.managePhone = op.phone
			console.log(this.$store);
			this.getLocation()
			that = this

			this.info = this.stepData[this.step - 1]
			//获取手机系统的信息（在这主要是获取状态栏和胶囊的高度）
			uni.getSystemInfo({
				success: (e) => {
					// this.compareVersion(e.SDKVersion, '2.5.0')
					let statusBar = 0
					let customBar = 0


					// #ifdef MP
					statusBar = e.statusBarHeight
					customBar = e.statusBarHeight + 45
					if (e.platform === 'android') {
						// this.$store.commit('SET_SYSTEM_IOSANDROID', false)
						customBar = e.statusBarHeight + 50
					}
					// #endif


					// #ifdef MP-WEIXIN
					statusBar = e.statusBarHeight
					// @ts-ignore
					const custom = wx.getMenuButtonBoundingClientRect()
					customBar = custom.bottom + custom.top - e.statusBarHeight
					// #endif

					// #ifdef APP-PLUS
					console.log('app-plus', e)
					statusBar = e.statusBarHeight
					customBar = e.statusBarHeight + 45
					// #endif


					// #ifdef H5
					statusBar = 0
					customBar = e.statusBarHeight + 45
					// #endif

					// 这里你可以自己决定存放方式，建议放在store中，因为store是实时变化的
					this.statusBarHeight = statusBar
					this.navHeight = customBar
				}
			})
		},
		onShow() {
			console.log(this.$store.state.pwdStatus);
			if (this.timer && this.step === 6) {
				this.read(HANDLE_0x9007) // 读取结果：0x9007返回的检测结果剩余时间
			}
		},
		methods: {
			back: debounce(() => {
				if (that.step === 1) {
					uni.navigateTo({
						url: '/pages/welcome/index'
					})
					return
				} else if ([3, 6].includes(that.step)) { // 扫一扫
					that.step = 1
					that.info = that.stepData[that.step - 1]
					that.close()
					return
				} else if (that.step === 7) {
					that.close()
					uni.navigateTo({
						url: '/pages/Healthrecords/index'
					})
					return
				}
				that.step--
				that.info = that.stepData[that.step - 1]
			}, 500),
			onConfirm: debounce(async () => {
				console.log(that.step)
				if (that.step === 1) {
					console.log('点击扫一扫');
					if (that.gps === false) {
						console.log('当前未授权定位');
						that.getLocation()
					} else if (that.gps === true) {
						// 扫码
						uni.scanCode({
							// onlyFromCamera: true,
							success: (res) => {
								console.log(res)
								const result = res.result
								that.scanDeviceName = result.split(',')[1]
								that.scanMac = result.split(',')[0]
								that.deviceNumber = that.scanDeviceName.padStart(9, '0')
								console.log('scanMac = ', that.scanMac)
								let pwdStatus = that.$store.state.pwdStatus
								Getresult({devceno:that.deviceNumber}).then(res=>{
									console.log(res,'测试');
									if(res.Code==801){
										//新数据
										if (that.scanDeviceName.length < 9) {
											that.deviceNumber = that.scanDeviceName.padStart(9, '0')
											console.log(that.deviceNumber, '111');
											const city = that.$store.state.vx_city
											if (pwdStatus) {
												CreateReagentResult({
													DeviceNo: that.deviceNumber,
													MacNo: that.scanMac,
													Phone: that.managePhone ? that.managePhone :
														that.$store.state.vx_u_info.Phone,
													Province: city.province,
													City: city.city,
													County: city.district,
													Address: city.address,
													Street: city.township,
													type: '微信小程序',
													managePhone: that.managePhone ? that.$store
														.state.vx_u_info.Phone : that.managePhone,
													name: that.$store.state.name,
													sex: that.$store.state.sex,
													age: that.$store.state.age,
													homeAddress: that.$store.state.homeAddress
												})
											} else {
												CreateReagentResult({
													DeviceNo: that.deviceNumber,
													MacNo: that.scanMac,
													Phone: that.managePhone ? that.managePhone :
														that.$store.state.vx_u_info.Phone,
													Province: city.province,
													City: city.city,
													County: city.district,
													Address: city.address,
													Street: city.township,
													type: '微信小程序',
										
												})
											}
										
										} else {
											that.deviceNumber = that.scanDeviceName
											console.log(that.deviceNumber, '222');
											const city = that.$store.state.vx_city
											if (pwdStatus) {
												CreateReagentResult({
													DeviceNo: that.deviceNumber,
													MacNo: that.scanMac,
													Phone: that.managePhone ? that.managePhone :
														that.$store.state.vx_u_info.Phone,
													Province: city.province,
													City: city.city,
													County: city.district,
													Address: city.address,
													Street: city.township,
													type: '微信小程序',
													managePhone: that.managePhone ? that.$store
														.state.vx_u_info.Phone : that.managePhone,
													name: that.$store.state.name,
													sex: that.$store.state.sex,
													age: that.$store.state.age,
													homeAddress: that.$store.state.homeAddress
												})
											} else {
												CreateReagentResult({
													DeviceNo: that.deviceNumber,
													MacNo: that.scanMac,
													Phone: that.managePhone ? that.managePhone :
														that.$store.state.vx_u_info.Phone,
													Province: city.province,
													City: city.city,
													County: city.district,
													Address: city.address,
													Street: city.township,
													type: '微信小程序',
												})
											}
											// 连接蓝牙
											// that.initBlue()
										}
										// 连接蓝牙
										that.initBlue()
									}else if(res.Code==200){
										//未完成上传的数据
										if(res.Data.DetectionResult==3){
											that.weiwancheng=true
											if (that.scanDeviceName.length < 9) {
												that.deviceNumber = that.scanDeviceName.padStart(9, '0')
												console.log(that.deviceNumber, '111');
												const city = that.$store.state.vx_city
												if (pwdStatus) {
													CreateReagentResult({
														DeviceNo: that.deviceNumber,
														MacNo: that.scanMac,
														Phone: that.managePhone ? that.managePhone :
															that.$store.state.vx_u_info.Phone,
														Province: city.province,
														City: city.city,
														County: city.district,
														Address: city.address,
														Street: city.township,
														type: '微信小程序',
														managePhone: that.managePhone ? that.$store
															.state.vx_u_info.Phone : that.managePhone,
														name: that.$store.state.name,
														sex: that.$store.state.sex,
														age: that.$store.state.age,
														homeAddress: that.$store.state.homeAddress
													})
												} else {
													CreateReagentResult({
														DeviceNo: that.deviceNumber,
														MacNo: that.scanMac,
														Phone: that.managePhone ? that.managePhone :
															that.$store.state.vx_u_info.Phone,
														Province: city.province,
														City: city.city,
														County: city.district,
														Address: city.address,
														Street: city.township,
														type: '微信小程序',
											
													})
												}
											} else {
												that.deviceNumber = that.scanDeviceName
												console.log(that.deviceNumber, '222');
												const city = that.$store.state.vx_city
												if (pwdStatus) {
													CreateReagentResult({
														DeviceNo: that.deviceNumber,
														MacNo: that.scanMac,
														Phone: that.managePhone ? that.managePhone :
															that.$store.state.vx_u_info.Phone,
														Province: city.province,
														City: city.city,
														County: city.district,
														Address: city.address,
														Street: city.township,
														type: '微信小程序',
														managePhone: that.managePhone ? that.$store
															.state.vx_u_info.Phone : that.managePhone,
														name: that.$store.state.name,
														sex: that.$store.state.sex,
														age: that.$store.state.age,
														homeAddress: that.$store.state.homeAddress
													})
												} else {
													CreateReagentResult({
														DeviceNo: that.deviceNumber,
														MacNo: that.scanMac,
														Phone: that.managePhone ? that.managePhone :
															that.$store.state.vx_u_info.Phone,
														Province: city.province,
														City: city.city,
														County: city.district,
														Address: city.address,
														Street: city.township,
														type: '微信小程序',
													})
												}
												// 连接蓝牙
												// that.initBlue()
											}
											// 连接蓝牙
											that.initBlue()
										}else{
											//已经成功上传的数据
											// console.log('后台存在数据，直接显示数据',res.Data.DetectionResult);
											let  arg1 =res.Data.DetectionResult
											that.step = 7
											const info = that.stepData[that.step - 1]
											if (arg1 === 1) {
												that.info = Object.assign({}, info, {
													result: arg1
												})
												that.$refs.popup.open('center')
											} else {
												that.info = Object.assign({}, info, {
													result: arg1,
													operateName: '返回'
												})
											}
										}
									}
									
								})
								
							}
						})
					}

				} else if (that.step === 2) { // 扫一扫
				console.log('扫一扫');
					that.step = 1
					that.info = that.stepData[that.step - 1]
				} else if (that.step === 3) {
					// console.log('读取9003');
					that.read(HANDLE_0x9003)
					// console.log('读取是否重复使用');
				
						that.step++
						that.info = that.stepData[that.step - 1]
					// }
					
				} else if (that.step === 4) {
					console.log(that.deviceId + '==>', HANDLE_0x9000)
					that.step++
					that.info = that.stepData[that.step - 1]
				} else if (that.step === 5) {
					// 开始检测
					that.getServices() // 检测是否断开
					if (that.resultTimer) {
						clearInterval(that.resultTimer)
					}
			        that.step = 6
			        that.info = that.stepData[that.step - 1]
					that.read(HANDLE_0x9004)
				} else if (that.step === 7) {
					uni.navigateTo({
						url: '/pages/welcome/index'
					})
					that.close()
				}
			}, 500),
			//软关机
			Shutdown() {
				console.log('关机');
				uni.showModal({
					title: '提示',
					content: '确认关机',
					success: function(res) {
						if (res.confirm) {
							console.log('用户点击确认关机');
							that.send_2(HANDLE_0x9004)
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					},

				});

				console.log('触发软关机');
			},
			onAdapter() {
				console.log('启动-适配器-监听器');
				uni.onBluetoothAdapterStateChange((e) => {
					console.log('监听到适配器的状态 =》', JSON.stringify(e))
					this.bleAdapter = e
					if (e.available === false && this.isBack === false) {
						// 扫一扫
						this.bleConnection = false
						this.step = 1
						this.info = this.stepData[this.step - 1]
						console.log('适配器不可用')
						// #ifdef MP-WEIXIN
						uni.showToast({
							title: `蓝牙适配器不可用`,
							icon: 'none',
							duration: 2000
						})
						// #endif
						uni.closeBluetoothAdapter({
							success: (res) => {
								console.log('关闭蓝牙适配器成功')
								console.log(res)
							}
						})
					}
				})
			},
			onConnection() {
				console.log('启动-连接状态-监听器');
				uni.onBLEConnectionStateChange((e) => {
					this.bleConnection = e.connected
					if (this.bleConnection === false && this.isBack === false) {
						this.bleAdapter = {
							available: false
						}
						// 扫一扫
						this.step = 1
						this.info = this.stepData[this.step - 1]
						console.log('连接失败')
						// #ifdef MP-WEIXIN
						uni.showToast({
							title: `与蓝牙设备连接失败`,
							icon: 'none',
							duration: 2000
						})
						// #endif
						uni.closeBluetoothAdapter({
							success: (res) => {
								console.log('关闭蓝牙适配器成功')
								console.log(res)
							}
						})
					}
					console.log('监听到蓝牙设备连接的状态 =》', JSON.stringify(e))
				})
			},
			// 初始化
			initBlue() {
				if (this.isStartDiscovery) {
					uni.stopBluetoothDevicesDiscovery({
						success: (res) => {
							console.log('停止搜索')
							console.log(res)
						}
					})
				}
				uni.openBluetoothAdapter({
					success: (res) => {
						console.log('初始化蓝牙成功', res)
						this.bleAdapter = {
							available: true
						};
						this.onAdapter()
						this.discovery()
					},
					fail: (err) => {
						uni.showModal({
							title: '提示',
							content: '请开启手机蓝牙！',
							showCancel: false,
							success: (res) => {
								if (res.confirm) {
									console.log('用户点击确定');
									uni.closeBluetoothAdapter({
										success: (res) => {
											console.log('关闭蓝牙适配器成功')
											console.log(res)
										}
									})
								}
							}
						});
						console.log('初始化蓝牙失败')
						console.error(err)
					}
				})
			},
			// 开始搜寻附近设备
			discovery() {
				if (!this.bleAdapter.available) {
					this.initBlue();
					return
				}
				uni.startBluetoothDevicesDiscovery({
						// allowDuplicatesKey: true,
					services: ['00009000-0000-1000-8000-00805F9B34FB'],
					success: (res) => {
						this.isStartDiscovery = true
						console.log('开始搜索')
						setTimeout(() => {
							if (this.isStartDiscovery) {
								this.stopDiscovery()
								uni.showToast({
									title: '未找到蓝牙设备',
									icon: 'none'
								})
							}
						}, 40000)
						uni.showToast({
							title: '正在寻找蓝牙',
							icon: 'none'
						});
						// 开启监听回调
						this.executeMethods()
						// uni.onBluetoothDeviceFound(this.found)
					},
					fail: (err) => {
						this.isStartDiscovery = false
						console.log('搜索失败')
						console.error(err)
					}
				})
			},
			// 找到新设备就触发该方法
			found(res) {
				// console.log(res,'found测试');
                 if(res.devices[0].advertisData){
					 if (!this.blueDeviceList.find(item => item.deviceId === res.devices[0].deviceId)) {
					 	this.blueDeviceList.push(res.devices[0]);
					 }
				 }
				console.log('当前设备数组',this.blueDeviceList);
			},
			//附近设备
			executeMethods() {
				// 开启监听回调
				uni.onBluetoothDeviceFound(this.found)
				uni.showToast({
					title: '正在搜索蓝牙...',
					icon: 'none',
					duration: 3000
				})
				// 3秒后执行方法2
				setTimeout(() => {
					this.stopDiscovery()
					console.log(this.blueDeviceList, '找到设备');
					console.log('当前设备编号', this.scanMac);
					this.blueDeviceList.forEach(item => {
						console.log(item);
						// console.log((item.localName).substring(3),'遍历设备号');
						if ((item.localName).substring(3) == this.scanMac) {
							this.blueDeviceList_1.push(item);
							console.log('配对成功', this.blueDeviceList_1);
							//开始连接
							this.setConnect()
						}
					})
				}, 3000);
			},
			// 循环设备列表，找到对应的设备
			setConnect() {
				console.log('启动循环');
				this.blueDeviceList_1.forEach(item => {
					console.log(item,'当前设备信息');
					console.log('循环中',item.advertisData,item.advertisServiceUUIDs);
					// if (item.advertisData && item.advertisServiceUUIDs) {
						const uuid = item.advertisServiceUUIDs[0]
						console.log('service uuid =', uuid, 'deviceId ', item.deviceId)
						const advertisData = ab2hex(item.advertisData)
						console.log(advertisData,'解密后的advertisData');
						const mac = advertisData.toUpperCase()
						console.log('当前mac',mac,mac.length);
						if (mac.length == 24) {
							console.log('mac = ', mac)
							console.log('当前信号强弱', item.RSSI);
							uni.request({
								url: `https://www.shlxkj.info/API/api/Decrypt/decryptMac`,
								method: 'GET',
								data: {
									macCode: mac
								},
								header: {
									Authorization: 'Bearer ' + store.state.vx_token,
									ApiKey: store.state.vx_token
								},
								success: (res) => {
									if (res.data.Code === 200) {
										// console.log('接口解码',res.data.Data);
										let mac_base64 = res.data.Data
										if (mac_base64.includes(this.scanMac)) {
											console.log('本板子解码后的mac地址', mac_base64);
											let phonenumber = this.$store.state.vx_u_info.Phone
											//查询是否存在关联
											debounce(GetReleted({
												mac: mac_base64
											}).then(res => {
												// console.log(res.Data);
												let arr = res.Data
												// console.log('现在的号码',phonenumber);
												// console.log('绑定的号码',res.Data[0]?.Number);
												if (arr.length == 0) {
													// console.log('没有绑定');
													debounce(CreateReleted({
														Mac: mac_base64,
														Number: this.$store.state.vx_u_info.Phone
													}).then(res => {
														// console.log('新增结果',res);
														if (res.Code == 200) {
															uni.showToast({
																title: '正在连接',
																icon: 'success',
																duration: 2000
															})

															// this.stopDiscovery()
															this.bleConnect(item)
															this.blueDeviceList_1=[]
														}
													}))
												} else {
													if (arr[0].Number == phonenumber) {
														console.log('绑定机链接');

														uni.showToast({
															title: '正在连接',
															icon: 'success',
															duration: 2000
														})
														// this.stopDiscovery()
														this.bleConnect(item)
														this.blueDeviceList_1=[]
													} else {
														uni.showToast({
															title: '本设备已被绑定',
															icon: 'error',
															duration: 2000
														})
														this.blueDeviceList_1=[]
													}
												}
											}))
										}
									}
								}
							});

						} else if (mac.length != 24) {
							console.log('老板子');
							//老板子
							if (mac.includes(this.scanMac)) {
								let phonenumber = this.$store.state.vx_u_info.Phone
								GetReleted({
									mac: mac
								}).then(res => {
									// console.log(res.Data);
									let arr = res.Data
									// console.log('现在的号码-老板子',phonenumber);
									// console.log('绑定的号码',res.Data[0].Number);
									if (arr.length == 0) {
										// console.log('没有绑定');

										debounce(CreateReleted({
											Mac: mac,
											Number: this.$store.state.vx_u_info.Phone
										}).then(res => {
											// console.log('新增结果',res);
											if (res.Code == 200) {
												uni.showToast({
													title: '正在连接',
													icon: 'success',
													duration: 2000
												})
												// this.stopDiscovery()
												this.bleConnect(item)
												this.blueDeviceList_1=[]
											}
										}))
									} else {
										if (arr[0].Number == phonenumber) {
											console.log('绑定机链接');
											uni.showToast({
												title: '正在连接',
												icon: 'success',
												duration: 2000
											})
											// this.stopDiscovery()
											this.bleConnect(item)
											this.blueDeviceList_1=[]
										} else {
											uni.showToast({
												title: '本设备已被绑定',
												icon: 'error',
												duration: 2000
											})
											this.blueDeviceList_1=[]
										}
									}
								})
							}
						}
					// }
				})
			},
			// 连接蓝牙
			async bleConnect(data) {
				if (this.scanDeviceName.length < 9) {
					this.deviceNumber = this.scanDeviceName.padStart(9, '0')
				} else {
					this.deviceNumber = this.scanDeviceName
				}
				uni.createBLEConnection({
					deviceId: data.deviceId,
					success: async (res) => {
						// console.log('连接成功', data)
						// this.read(HANDLE_0x9005)
						// console.log('连接后读取9005结果');
						 console.log('连接时状态',this.weiwancheng);
						 
						 // 2秒后页面切换到（连接成功开始检测）
						 setTimeout(() => {
						if(this.weiwancheng==false){                 
							if(this.JG==false){
								if(this.JG_2==1){
									this.step = 6
									this.info = this.stepData[this.step - 1]
								}else{
									this.step = 3
									this.info = this.stepData[this.step - 1]
								}
								
							}
						}
						 }, 2000);
						
						
						this.deviceId = data.deviceId
						this.serviceId = HANDLE_0x9000
						this.DetectionType = data.localName
						uni.showToast({
							title: `与蓝牙设备连接成功`,
							icon: 'success',
							duration: 2000
						})
						this.getServices()
					},
					fail: (err) => {
						console.log(err)
						if (err.errno === 1509007) {
							uni.showToast({
								title: `蓝牙设备已连接`,
								icon: 'success',
								duration: 2000
							})
							// this.deviceNumber = this.scanDeviceName.padStart(9, '0')
							this.getServices()
						} else {
							// 扫一扫
							this.step = 1
							this.info = this.stepData[this.step - 1]
							console.log('连接失败')
							uni.showToast({
								title: `与蓝牙设备连接失败`,
								icon: 'none',
								duration: 2000
							})
							console.error(err)
						}
					}
				})
			},
			// 停止搜索
			stopDiscovery() {
				uni.stopBluetoothDevicesDiscovery({
					success: (res) => {
						this.isStartDiscovery = false
						console.log('停止成功')
						console.log(res)
					},
					fail: (err) => {
						console.log('停止失败')
						console.error(err)
					}
				})
			},
			// 获取服务
			getServices() {
				// deviceId XHA2306001002 93045D85-A711-C8CC-1DBA-6E08EC5CCA2C
				uni.getBLEDeviceServices({
					deviceId: this.deviceId, // 设备ID，在上一步【4】里获取
					success: async (res) => {
						console.log(this.deviceId + ' getBLEDeviceServices => ', res)
						
						this.getCharacteristics()
						//   await sleep(1000)
						//   this.read(HANDLE_0x2A00)
						// }
					},
					fail: (err) => {
						console.error(err)
						if (this.checkTimer) {
							clearInterval(this.checkTimer)
							this.checkTimer = null
						}
						if (this.timer) {
							clearInterval(this.timer)
							this.timer = null
						}
						if ([-1, 10000, 10002, 10003, 10004, 10005, 10006].includes(err.errCode)) {
							this.close()
							uni.showModal({
								content: '请检查设备是否正常运行，或重新扫描连接，如果设备显示红灯，请更换设备。',
								showCancel: false,
								success(res) {
									if (res.confirm) {
										// 扫一扫
										that.step = 1
										that.info = that.stepData[that.step - 1]
									}
								}
							})
						}
					}
				})
			},
			
			// 获取特征值
			getCharacteristics() {
				uni.getBLEDeviceCharacteristics({
					deviceId: this.deviceId, // 设备ID
					serviceId: this.serviceId, // 服务UUID
					success: (res) => {
						console.log(this.serviceId + 'characteristics =', res)
						this.read(HANDLE_0x9003)
						// if(this.weiwancheng==true){
							//扫过码了但未完成上传，直接跳转到倒计时页面
							if (this.resultTimer) {
								clearInterval(this.resultTimer)
							}
							this.read(HANDLE_0x9004)
						// }else{
							// this.read(HANDLE_0x9004)
							// console.log(this.HFX,'当前倒计时时间');
							// if(this.HFX=0){
							// 	console.log('测试结束');
							// }else{
							// }
						// }
					},
					fail: (err) => {
						console.error(err)
						if ([10002, 10003, 10006].includes(err.errCode)) {
							this.close()
							uni.showModal({
								content: '请检查设备是否正常运行，或重新扫描连接。',
								showCancel: false,
								success(res) {
									if (res.confirm) {
										// 扫一扫
										that.step = 1
										that.info = that.stepData[that.step - 1]
									}
								}
							})
						}
					}
				})
			},
			// 【8】开启消息监听
			notify(characteristicId) {
				console.log(characteristicId)
				uni.notifyBLECharacteristicValueChange({
					deviceId: this.deviceId, // 设备ID，在【4】里获取到
					serviceId: this.serviceId, // 服务UUID，在【6】里能获取到
					characteristicId, // 特征值，在【7】里能获取到
					state: true, // 启用消息监听
					success: (res) => {
						console.log(res)
						// 接受消息的方法
						this.listenValueChange()
					},
					fail: async (err) => {
						console.log('开启消息监听失败')
						console.error(err)
					}
				})
			},
			// 监听消息变化
			listenValueChange() {
				/**
				 * {characteristics: [
				 * {properties:  { writeDefault: false, notify: false, write: false, indicate: false, read: true, writeNoResponse: false}, uuid: "00009001-0000-1000-8000-00805F9B34FB"},
				 * {properties: {writeDefault: false, notify: false, write: false, indicate: false, read: true, writeNoResponse: false}, uuid: "00009002-0000-1000-8000-00805F9B34FB"},
				 * {properties: {writeDefault: false, notify: false, write: false, indicate: false, read: true, writeNoResponse: false}, uuid: "00009003-0000-1000-8000-00805F9B34FB"},
				 * {properties: {writeDefault: true, notify: true, write: true, indicate: false, read: true, writeNoResponse: false}, uuid: "00009004-0000-1000-8000-00805F9B34FB"},
				 * {properties: {writeDefault: true, notify: false, write: true, indicate: false, read: true, writeNoResponse: false}, uuid: "00009005-0000-1000-8000-00805F9B34FB"},
				 * {properties: {writeDefault: false, notify: false, write: false, indicate: false, read: true, writeNoResponse: false}, uuid: "00009006-0000-1000-8000-00805F9B34FB"},
				 * {properties: {writeDefault: false, notify: false, write: false, indicate: false, read: true, writeNoResponse: false}, uuid: "00009007-0000-1000-8000-00805F9B34FB"}],
				 * deviceId: "3DB85199-BEE5-A05C-E67A-29F303ABA225", serviceId: "00009000-0000-1000-8000-00805F9B34FB", errno: 0, errMsg: "getBLEDeviceCharacteristics:ok", errCode: 0}
				 */
				uni.onBLECharacteristicValueChange(async res => {
					// console.log('onBLECharacteristicValueChange', res)
					// 结果里有个value值，该值为 ArrayBuffer 类型，所以在控制台无法用肉眼观察到，必须将该值转换为16进制
					const resHex = ab2hex(res.value)
					console.log('ab2hex ===', resHex)
					if (res.characteristicId === HANDLE_0x9001) {
						const data = await this.aesDecrypt(resHex, '0x9001')
						console.log("读取结果：0x9001返回的唯一编号" + data);
						// 句柄0x9002对应检测项目(ASCII码16个字节)，
					} else if (res.characteristicId === HANDLE_0x9002) {
						const data = await this.aesDecrypt(resHex, '0x9002')
						console.log("读取结果：0x9002返回的检测项目" + data);
						// 句柄0x9003对应批次号(ASCII码8个字节)，
					} else if (res.characteristicId === HANDLE_0x9003) {
						// const data = await this.aesDecrypt(resHex, '0x9003')
						// console.log("读取结果：0x9003返回的批次号" + data);
						const num = resHex.substr(-18)
						this.key = baseSecret + num
						console.log('key => ', this.key)
						// 句柄0x9004对应检测状态(1个字节)，
					} else if (res.characteristicId === HANDLE_0x9004) {
						const data = await this.aesDecrypt(resHex, '0x9004')
						console.log("读取结果：0x9004返回的检测状态" + data);
						// await this.read(HANDLE_0x9006)
						if(this.weiwancheng==true){
							this.step = 6
							this.info = this.stepData[this.step - 1]
							if (1 === data) {
								// this.HFX=data
								console.log("读取结果：0x9004返回的=" + data + "=已开始检测，继续读取倒计时");
								this.read(HANDLE_0x9007) // 读取结果：0x9007返回的检测结果剩余时间
								if (this.checkTimer) {
									clearInterval(this.checkTimer)
									this.checkTimer = null
								}
							} else if (2 === data) {
								console.log("读取结果：0x9004返回的=" + data + "=设备异常！！");
								this.step = 7
								const info = this.stepData[this.step - 1]
								let arg1 = 4
								this.info = Object.assign({}, info, {
									result: arg1,
									operateName: '返回'
								})
							
							} else {
								this.times = -1
								console.log("读取结果：0x9004返回的：" + data + "==" + (0 === data ? "未开始检测" : "未知状态") +
									",等待5秒后重新查询状态");
								if (this.resultTimer) {
									clearTimeout(this.resultTimer)
									this.resultTimer = null
								}
								if (this.checkTimer) {
									clearInterval(this.checkTimer)
									this.checkTimer = null
								}
								this.resultTimer = setTimeout(async () => {
									this.read(HANDLE_0x9004)
								}, 5000)
								this.checkTimer = setInterval(() => {
									this.getServices()
								}, 2000)
							}
						}else{
							if (1 === data) {
								console.log("读取结果：0x9004返回的=" + data + "=已开始检测，继续读取倒计时");
								this.JG_2=data
								this.read(HANDLE_0x9007) // 读取结果：0x9007返回的检测结果剩余时间
								if (this.checkTimer) {
									clearInterval(this.checkTimer)
									this.checkTimer = null
								}
							} else if (2 === data) {
								console.log("读取结果：0x9004返回的=" + data + "=设备异常！！");
								this.step = 7
								const info = this.stepData[this.step - 1]
								let arg1 = 4
								this.info = Object.assign({}, info, {
									result: arg1,
									operateName: '返回'
								})
							
							} else {
								this.times = -1
								console.log("读取结果：0x9004返回的：" + data + "==" + (0 === data ? "未开始检测" : "未知状态") +
									",等待5秒后重新查询状态");
								if (this.resultTimer) {
									clearTimeout(this.resultTimer)
									this.resultTimer = null
								}
								if (this.checkTimer) {
									clearInterval(this.checkTimer)
									this.checkTimer = null
								}
								this.resultTimer = setTimeout(async () => {
									this.read(HANDLE_0x9004)
								}, 5000)
								this.checkTimer = setInterval(() => {
									this.getServices()
								}, 2000)
							}
						}
						
						// 句柄0x9005对应检测结果(5个字节，1个字节为结果，四个字节为过程数据)，结果为0为阴性，1为阳性，2为异常。
					} else if (res.characteristicId === HANDLE_0x9005) {
						console.log('9005X返回');
						// if (this.processIndex === 0) {
							const data = await this.aesDecrypt(resHex, '0x9005')
							
							let  arg1 = data.arg1 // 0 阴性 1 阳性 2 异常 4 设备异常
							const  arg2  = data.arg1 // 0 阴性 1 阳性 2 异常 4 设备异常
							console.log("读取结果：0x9005返回的检测结果" + arg2);
							
							// if (arg1 > 2) {
							//   // 继续读取过程值
							//   this.processIndex = 0
							//   this.startWriteProgress()
							//   return
							// }

							// 获取结果值
							await aesDecryptjieguozhi({
								Data: resHex,
								Key: this.key,
								Handle: '0x9005'
							}).then(res => {
								console.log('9005X结果值返回', res.Data.jieguozhi);
								this.$store.commit('$uStore', {
									name: 'jieguozhi',
									value: res.Data.jieguozhi
								})
								console.log('存入的结果值', this.$store.state.jieguozhi);

							})
							
							//动态阈值 
							
							await aesDecryptGetAPiyuzhi({devicenono:this.deviceNumber}).then(res=>{
								console.log('获取阈值',res.Data[0]?.Yuzhi);
								if(res.Data[0]?.Yuzhi==undefined){
									console.log('接口无返回阈值');
								}else{
									if(res.Data[0].Yuzhi>=this.$store.state.jieguozhi){
										console.log('结果值小于与阈值，阴性');
										arg1 =0
									}else if(res.Data[0].Yuzhi<=this.$store.state.jieguozhi){
										console.log('结果值大于与阈值，阳性');
										arg1 =1
									}
								}
							})
							this.stopBluetooth()
							// 将假阈值跟结果值进行比较，如果结果值小于阈值，则是无反应；结果值大于阈值，
							// 则是有反应；如果拿不到假阈值（返回NULL）,则继续当前的逻辑
							this.step = 7
							const info = this.stepData[this.step - 1]
							if (arg1 === 1) {
								this.info = Object.assign({}, info, {
									result: arg1
								})
							} 
							// else if (arg1 === 4) {
							// 	this.info = Object.assign({}, info, {
							// 		result: arg1,
							// 		operateName: '返回'
							// 	})
							// } 
							else {
								this.info = Object.assign({}, info, {
									result: arg1,
									operateName: '返回'
								})
							}
							const city = this.$store.state.vx_city
							let yuzhi = (this.$store.state.yuzhi).toString()
							let jieguozhi = (this.$store.state.jieguozhi).toString()
							console.log(yuzhi);
							const res = await UpReagentResult({
								DeviceNo: this.deviceNumber,
								MacNo: this.scanMac,
								DetectionType: this.DetectionType,
								// DetectionTime: new Date(),
								Phone: this.$store.state.vx_u_info.Phone,
								Province: city.province,
								City: city.city,
								County: city.district,
								Address: city.address,
								Street: city.township,
								DetectionResult: arg1,//判断过的数据
								RealDetectionResult:arg2,//真实数据
								Yuzhi: yuzhi,
								Jieguozhi: jieguozhi,
								type: '微信小程序'
							})
							if (res.Code === 200 || res.Code === 801) {
								console.log('上报成功结果 ===》', res.Data)
								
								if (arg1 === 1) {
									this.$refs.popup.open('center')
								}
							}
							// const ReportRes = await ReportedData({
							//   Result: arg1,
							//   DeviceNo: this.deviceNumber,
							//   Key: this.key,
							//   ReportedDatas: this.process.map(item => {
							//     return {
							//       Data: item
							//     }
							//   })
							// })
							// if (ReportRes.Code === 200) {
							//   console.log('上报过程完成')
							// }
						// } else if (this.processIndex !== 0 && this.processIndex < 195) {
						// 	console.log("读取过程值次数：", this.processIndex)
						// 	this.process.push(resHex)
						// 	this.processIndex++
						// 	await this.read(HANDLE_0x9005) // 读取过程值：0x9005返回的检测结果
						// } else if (this.processIndex >= 195) {
						// 	console.log("读取过程值次数结束：", this.processIndex)
						// 	this.process.push(resHex)
						// 	this.processIndex = 0
						// 	this.startWriteProgress()
						// }
						// 句柄0x9006对应检测开始时间(4个字节，单位为秒，未开始为0，结束为0xffffffff)，
					} else if (res.characteristicId === HANDLE_0x9006) {
						const data = await this.aesDecrypt(resHex, '0x9006')
						console.log("读取结果：0x9006返回" + data);
						await aesDecrypt2({
							Data: resHex,
							Key: this.key,
							Handle: '0x9006'
						}).then(res => {
							console.log('9006X阈值返回', res, res.Data.yz);
							this.$store.commit('$uStore', {
								name: 'yuzhi',
								value: res.Data.yz
							})
							console.log('存入的阈值', this.$store.state.yuzhi);
							// console.log(this.$store.state.yuzhi);
						})


						// 句柄0x9007对应检测结果剩余时间(4个字节，单位为秒，未开始为0xffffffff，结束为0)。
					} else if (res.characteristicId === HANDLE_0x9007) {
						this.read(HANDLE_0x9006)
						const data = await this.aesDecrypt(resHex, '0x9007')
						console.log("读取结果：0x9007返回的检测结果剩余时间" + data);
						this.times = data
						let end = Date.now() + (data + 1) * 1000;
						// 倒计时结束请求获取结果
						let times = data
						let text = data
						if (this.timer) {
							clearInterval(this.timer)
							this.timer = null
						}
						console.log("当前时间戳", Date.now() + "==" + end);
						this.timer = setInterval(async () => {
							this.HFX=times
							times = parseInt((end - Date.now()) / 1000)
							console.log('倒计时', times)
							console.log('测试倒计时', text);
							this.getServices()
							if (times <= 0) {
								times = 0
								clearInterval(this.timer)
								this.timer = null
								// 开始读取过程值
								this.processIndex = 0
								this.JG=true
								this.read(HANDLE_0x9005)
							}
						}, 1000)
					}
				})
			},
			async startWriteProgress() {
				console.log('startWriteProgress ', this.processIndex)
				await this.send(HANDLE_0x9005, this.processIndex)
				// if (this.processIndex === 1) {
				//   this.notify(HANDLE_0x9005)
				// } else {
				// }
				this.read(HANDLE_0x9005)
			},

			// aes解密方法
			async aesDecrypt(word, handle) {
				// uni.showLoading({
				//   title: 'loading'
				// })
				const res = await AESDecrypt({
					Data: word,
					Key: this.key,
					Handle: handle
				})
				// uni.hideLoading()
				if (res.Code === 200) {
					return res.Data
				}
			},
			// aes加密方法
			async aesEncrypt(word) {
				const res = await AESEncrypt({
					Data: word,
					Key: this.key
				})
				if (res.Code === 200) {
					return res.Data
				}
			},
			// 向设备发送数据
			async send(characteristicId, type = 0) {
				console.log(`写入${characteristicId}，值为${type}`)
				let Data = ''
				if (type === 0) {
					Data = '00000000000000000000000000000000'
				} else {
					Data = '10000000000000000000000000000000'
				}
				const res = await AESEncrypt({
					Data,
					Key: this.key
				})
				console.log('写入', Data, res.Data)
				if (res.Code === 200) {
					const buffer = new ArrayBuffer(res.Data)
					uni.writeBLECharacteristicValue({
						deviceId: this.deviceId, // 设备ID，在【4】里获取到
						serviceId: this.serviceId, // 服务UUID，在【6】里能获取到
						characteristicId, // 特征值，在【7】里能获取到
						value: buffer,
						success: async (res) => {
							// if (characteristicId === HANDLE_0x9005) {
							//   this.read(HANDLE_0x9005) // 读取结果：0x9005返回的检测结果
							// }
							console.log('写入指令发送成功', res)
							await sleep(100)
							await this.getCharacteristics()

						},
						fail: (err) => {
							console.log('写入指令发送失败', err)
						}
					})
				}
			},
			hexStringToArrayBuffer(hexString) {
				const hex = hexString.replace(/\s/g, ''); // 移除空格
				const bytes = new Uint8Array(hex.length / 2);
				for (let i = 0; i < hex.length; i += 2) {
					bytes[i / 2] = parseInt(hex.substr(i, 2), 16);
				}
				return bytes.buffer;
			},
			async send_2(characteristicId) {
				console.log(`写入${characteristicId}`)
				let Data = ''
				Data = '73687574000000000000000000000000'
				const res = await AESEncrypt({
					Data,
					Key: this.key
				})
				// const buffer = new ArrayBuffer(res.Data)

				console.log('写入', Data, res.Data)
				let closekey = (res.Data).toUpperCase()
				console.log(closekey.toUpperCase());
				if (res.Code === 200) {
					// 向蓝牙设备发送一个0x00的16进制数据
					// const buffer = new ArrayBuffer(closekey)
					const buffer = this.hexStringToArrayBuffer(closekey);
					// const dataView = new DataView(buffer)
					// for (var i = 0; i < closekey.length; i++) {  
					//       dataView.setUint8(i, closekey.charAt(i).charCodeAt())
					//     }
					console.log(buffer, '命令值');

					uni.writeBLECharacteristicValue({
						deviceId: this.deviceId, // 设备ID，在【4】里获取到
						serviceId: this.serviceId, // 服务UUID，在【6】里能获取到
						characteristicId, // 特征值，在【7】里能获取到
						value: buffer,
						writeType: 'write',
						success: async (res) => {
							this.$refs.popup.close()
							console.log('写入指令发送成功', res)
							// await sleep(100)
							// await this.getCharacteristics()

						},
						fail: (err) => {
							console.log('写入指令发送失败', err)
						}
					})
				}

			},
			// 【11】读取数据
			read(characteristicId) {
				console.log('read ', this.deviceId, this.serviceId, characteristicId)
				uni.readBLECharacteristicValue({
					deviceId: this.deviceId,
					serviceId: this.serviceId,
					characteristicId,
					success: (res) => {
						console.log('读取指令发送成功')
						// 接受消息的方法
						this.listenValueChange()
					},
					fail: (err) => {
						console.log('读取指令发送失败', err)
					}
				})
			},
			//停止消息监听
				  stopBluetooth(characteristicId) {
				        // 停止监听蓝牙特征值变化
				        uni.offBLECharacteristicValueChange()
						 console.log('停止获取蓝牙特征值')
			// 	        uni.cancelBLECharacteristicValueChange({
			// 	          deviceId: this.deviceId,
			// 	          serviceId: this.serviceId,
			// 	          characteristicId,
			// 	          success: () => {
			// 	            console.log('停止获取蓝牙特征值')
			
			// 	          },
			// 	          fail: (err) => {
			// 	            console.log('停止获取蓝牙特征值失败', err)
			// 	          }
			// 	        })
				 
			},
			async close() {
				this.times = 0
				if (this.resultTimer) {
					clearInterval(this.resultTimer)
					this.resultTimer = null
				}
				if (this.timer) {
					clearInterval(this.timer)
					this.timer = null
				}
				if (this.checkTimer) {
					clearInterval(this.checkTimer)
					this.checkTimer = null
				}
				// if (this.processTimer) {
				//   clearTimeout(this.processTimer)
				//   this.processTimer = null
				// }
				if (this.$refs.testCheck) {
					this.$refs.testCheck.getReset()
				}
				this.$refs.popup.close()
				//断开蓝牙连接
				uni.closeBLEConnection({
					//设备ID
					deviceId: this.deviceId,
					success(res) {
						console.log('断开蓝牙连接', res)
					}
				});
				sleep(1000)
				//关闭蓝牙模块
				uni.closeBluetoothAdapter({
					success(res) {
						console.log('关闭蓝牙模块', res)
					}
				})
				sleep(1000)
			},
			async onCancel() {
				const res = await UpdateReagentResult({
					DeviceNo: this.deviceNumber,
					Phone: this.$store.state.vx_u_info.Phone,
					IsNeedContact: false
				})
				console.log(res);
				if (res.Code === 200) {
					this.close()
					this.$refs.popup.close()
					uni.navigateTo({
						url: '/pages/welcome/index'
					})
				}
			},
			async onNeed() {
				const res = await UpdateReagentResult({
					DeviceNo: this.deviceNumber,
					Phone: this.$store.state.vx_u_info.Phone,
					IsNeedContact: true
				})
				console.log(res);
				if (res.Code === 200) {
					this.close()
					this.$refs.popup.close()
					uni.navigateTo({
						url: '/pages/hospital/index'
					})
				}
			},
			getLocation(tag) {
				uni.getLocation({
					type: 'wgs84',
					success: async (res) => {
						//res.longitude,res.latitude分别为当前经度，纬度
						const response = await ConvertCoordinate({
							Locations: [res.longitude, res.latitude].join(',')
						})
						console.log(response.Data.regeocode)
						if (response.Code === 200) {
							const {
								province,
								city,
								district,
								township
							} = response.Data.regeocode.addressComponent
							const address = response.Data.regeocode.formatted_address
							this.$store.commit('$uStore', {
								name: 'vx_city',
								value: {
									province,
									city,
									district,
									township,
									address
								}
							})
							this.gps = true
							console.log(this.gps);
							// if (tag) {
							//   uni.navigateTo({
							//     url: '/pages/login/index'
							//   })
							// }
						}
					},
					fail: (err) => {
						console.log(err)
						this.gps = false
						uni.showModal({
							title: '提示',
							content: '使用本设备时，请开启手机定位！',
							showCancel: false,
							success: (res) => {
								if (res.confirm) {
									console.log('用户点击确定');
									uni.openSetting({
										success: function(res) {
											// 在成功回调中判断用户是否已开启位置权限，并进行相应处理
											if (res.authSetting[
												'scope.userLocation']) {
												// 用户已开启位置权限，可以重新调用 uni.getLocation 获取位置信息
												console.log('调用');
											}
										}
									});
								}
							}
						});
					}
				});
			},
		}
	}
</script>

<style lang="scss" scoped>
	.page {
		width: 100vw;
		height: 100vh;
		background-color: #1658CE;
		position: relative;
		display: flex;
		flex-direction: column;

		.nav-style {
			position: fixed;
			top: 0;
			right: 0;
			left: 0;
			z-index: 1000;
			display: flex;
			padding-left: 23rpx;
			align-items: center;
			justify-content: center;

			.small-logo {
				width: 100rpx;
				height: 35rpx;
			}

			.back-img {
				width: 36rpx;
				height: 36rpx;
				position: absolute;
				left: 23rpx;
				bottom: 0;
				margin: auto;
			}
		}

		.process-wrap {
			padding-bottom: 50rpx;
			box-sizing: border-box;
		}

		.wrap {
			flex: 1;
			width: 100%;
			margin-top: 36rpx;
			overflow: hidden;
		}

		.popup-wrap {
			width: 615.38rpx;
			height: 617.31rpx;
			padding: 42rpx;
			box-sizing: border-box;
			position: relative;
			border-radius: 30rpx;

			.popup-bg {
				width: 615.38rpx;
				height: 617.31rpx;
				position: absolute;
				top: 0;
				left: 0;
				z-index: 0;
			}

			.popup-container {
				width: 100%;
				height: 100%;
				position: absolute;
				top: 0;
				left: 0;
			}

			.popup-title {
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				text-align: center;
				margin-top: 34rpx;

				.popup-img {
					width: 130rpx;
					height: 150rpx;
				}

				.popup-text {
					margin-top: 60rpx;
					margin-left: 22rpx;
					font-size: 32rpx;
					font-weight: bold;
					color: #000000;
				}
			}

			.popup-content {
				width: 515rpx;
				margin: 35rpx auto;
				font-size: 27rpx;
				font-weight: 400;
				color: #333333;
				line-height: 40rpx;
				text-align: center;
			}

			.popup-btn-wrap {
				width: 540.38rpx;
				position: absolute;
				left: 0;
				right: 0;
				bottom: 42rpx;
				margin: auto;
				display: flex;
				justify-content: space-between;
			}

			.popup-btn {
				width: 250rpx;
				height: 85rpx;
				line-height: 85rpx;
				font-size: 28rpx;
				font-weight: 400;
				text-align: center;
				border-radius: 15rpx;
				margin-left: 10rpx;

				&.cancel {
					color: #333333;
					background: #EBEBED;
				}

				&.need {
					background: #1E64E1;
					color: #ffffff;
				}
			}

			.popup-btn-close {
				width: 230rpx;
				height: 85rpx;
				line-height: 85rpx;
				font-size: 28rpx;
				font-weight: 400;
				text-align: center;
				border-radius: 15rpx;
				margin-left: 10rpx;

				&.cancel {
					color: #333333;
					background: #EBEBED;
				}
			}
		}
	}
</style>